const Router = require('koa-router');
const router = new Router();
const tool = require('../../tools/tool')
const {db, QueryTypes, DataTypes} = require("../../models/db");

// 计算政策兑付
router.post('/pay/calcDf', async ctx => {
    let user = ctx.user
    let body = ctx.request.body
    let formData = body.formData
    let tenantId = user.tenantId;
    let id = formData.id;
    let endDate = formData.endDate;
    let dfType = formData.dfType?formData.dfType:'';
    let brandId = formData.brandId?formData.brandId:0;
    let invId = formData.invId?formData.invId:0;
    if(!invId && !brandId) {
        return ctx.err('品牌或者商品必选其一')
    }
    let sendType = formData.sendType;
    if(!endDate) return ctx.err('请选择截止日期')
    if(tool.dayjs(endDate).isAfter(tool.getDay())) {
        return ctx.err('截止时间不能大于今天')
    }
    if(sendType.length === 0) return ctx.err('请选择赠品类型')
    let send = []
    let sendList = []
    sendType.map(row => {
        send.push(`'${row}'`)
        sendList.push(`${row}`)
    })
    let listSql = `
        with bills as (select b.id invoiceInfoId,
                                  a.tenantId,
                                  b.iid invoiceId,
                                  b.invName,
                                  b.brandId,
                                  b.invId,
                                  b.spec,
                                  b.qtyReal * b.calNum   qty,
                                  b.unit,
                                  b.send,
                                  b.sendPrice
                           from invoice a
                                    inner join v_main_info b on a.tenantId = b.tenantId and a.id = b.iid 
                           where a.tenantId = ${tenantId} 
                             and b.id not in (select b.invoiceInfoId from send_df a inner join send_df_detail b on a.tenantId=b.tenantId and a.id=b.sendDfId and a.tenantId=${tenantId} and a.billState='accounted')
                             and a.billState = 'accounted' 
                             and a.billDate <= '${endDate}' 
                             and b.send in (${send.join(',')}) 
                           and (${brandId}=0 or b.brandId=${brandId}) 
                           and (${invId}=0 or b.invId=${invId}) 
        )select * from bills 
    `
    let list = await db.query(listSql, {type: QueryTypes.SELECT})
    if(list.length === 0) {
        return ctx.err('没要查询到需要兑付的数据')
    }
    else {
        let ret = await db.transaction(async () => {
            let model = null
            if(id) {
                model = await db.models['sendDf'].findOne({
                    where:{
                        tenantId,
                        id
                    }
                })
            }
            else {
                model = db.models['sendDf'].build()
                model.cby = user.id
                model.createdAt = tool.getTime()
            }
            model.billDate = tool.getDay()
            model.tenantId = tenantId
            model.tempId = tool.uuid()
            model.endDate = endDate
            model.brandId = brandId
            model.invId = invId
            model.sendType = sendList.join(',')
            model.dfType = dfType
            model.amount = 0
            await model.save()
            let sqls = `
                with bills as (select b.id invoiceInfoId,
                                      a.tenantId,
                                      b.iid invoiceId,
                                      b.invName,
                                      b.brandId,
                                      b.invId,
                                      b.spec,
                                      b.qtyReal * b.calNum   qty,
                                      b.unit,
                                      b.send,
                                      isnull(b.sendPrice, 0) sendPrice
                               from invoice a
                                        inner join v_main_info b on a.tenantId = b.tenantId and a.id = b.iid 
                               where a.tenantId = ${tenantId} 
                                 and a.billState = 'accounted' 
                                 and a.billDate <= '${endDate}' 
                                 and b.send in (${send.join(',')}) 
                               and (${brandId}=0 or b.brandId=${brandId}) 
                               and (${invId}=0 or b.invId=${invId}) 
                )
                insert into send_df_detail(tenantId, sendDfId, invId, brandId, spec, unit, sendPrice, dz, zz, cl, xl, ht, ky, zy, send, qty, amount, invoiceInfoId, invoiceId)
                select tenantId,${model.id} sendDfId,invId,brandId,spec,unit,sendPrice, 
                   case when send=N'代赠' then qty else 0 end dz,
                   case when send=N'自赠' then qty else 0 end zz,
                   case when send=N'陈列' then qty else 0 end cl,
                   case when send=N'销量' then qty else 0 end xl,
                   case when send=N'合同' then qty else 0 end ht,
                   case when send=N'开业' then qty else 0 end ky,
                   case when send=N'赠饮' then qty else 0 end zy,
                   send,
                   qty,
                   (qty/spec)*sendPrice amount,
                   invoiceInfoId,
                   invoiceId
                   from bills 
            `
            if(id) {
                await db.models['sendDfDetail'].destroy({
                    where: {
                        tenantId,
                        sendDfId: id,
                    }
                })
            }
            await db.query(sqls, {type: QueryTypes.INSERT})
            return model
        })
        let resql = `
           with bills as (
               select a.tenantId,a.invId,b.name invName,b.brandName,
                      a.spec,a.unit,a.sendPrice,sum(a.dz) dz,sum(a.zz) zz,sum(a.cl) cl,sum(a.xl) xl,sum(a.ht) ht,sum(a.ky) ky,sum(a.zy) zy,sum(a.qty) qty
               from send_df_detail a inner join v_goods b on a.tenantId=b.tenantId and a.invId=b.id
               where sendDfId=${ret.id} 
               GROUP BY a.tenantId, a.invId, b.name, b.brandName, a.spec, a.unit, a.sendPrice
           ) select tenantId, invId, invName, brandName, spec, unit, sendPrice, 
                    dz/spec dz, zz/spec zz, cl/spec cl, xl/spec xl, ht/spec ht, ky/spec ky, zy/spec zy, qty/spec qty, (qty/spec)*sendPrice amount from bills
           order by invName
        `
        let res = await db.query(resql, {type: QueryTypes.SELECT})
        return ctx.suc('', {
            id: ret.id,
            list: res
        })
    }
})



module.exports = router;
